import { BadRequestException, Catch, HttpException, Type, HttpStatus, ArgumentsHost } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { isObject } from 'class-validator';
import { EntityNotFoundError, EntityPropertyNotFoundError, QueryFailedError } from "typeorm";


@Catch()
export class AppFilter<T = Error> extends BaseExceptionFilter {
    protected resException: Array<{ class: Type<Error>, status?: number } | Type<Error>> = [
        {
            class: EntityNotFoundError,
            status: HttpStatus.NOT_FOUND
        },
        {
            class: EntityPropertyNotFoundError,
            status: HttpStatus.BAD_REQUEST
        },
        {
            class: QueryFailedError,
            status: HttpStatus.NOT_FOUND
        }
    ]

    catch(exception: T, host: ArgumentsHost) {
        const application = this.applicationRef || (this.httpAdapterHost.httpAdapter)!
        //判断 传来的 exception 在不在resException里
        const resException = this.resException.find(item => {
            'class' in item ? exception instanceof item.class : exception instanceof item
        })

        //如果不在 且 不属实 HttpException
        if (!resException && !(exception instanceof HttpException)) {
            return this.handleUnknownError(exception, host, application)
        }
        //在的话
        let res: object | string = ''
        let status = HttpStatus.INTERNAL_SERVER_ERROR
        if (exception instanceof HttpException) {
            res = exception.getResponse()
            status = exception.getStatus()
        } else if (resException) {
            const e = exception as Error
            res = e.message
            if ('class' in resException && resException.status) {
                status = resException.status;
            }

        }

        const message=isObject(res)?res:{
        message:res,
        statusCode:status
        }

        application.reply(host.getArgByIndex[1],res,status)
    }
}